package org.jeecg.config;

import com.baomidou.mybatisplus.core.parser.ISqlParser;
import com.baomidou.mybatisplus.extension.plugins.tenant.TenantHandler;
import com.baomidou.mybatisplus.extension.plugins.tenant.TenantSqlParser;
import com.google.common.collect.Lists;
import lombok.extern.slf4j.Slf4j;
import net.sf.jsqlparser.expression.Expression;
import org.jeecg.common.util.TenantUtil;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import com.baomidou.mybatisplus.extension.plugins.PaginationInterceptor;
import com.baomidou.mybatisplus.extension.plugins.PerformanceInterceptor;

import java.util.ArrayList;
import java.util.List;

/**
 * 单数据源配置（jeecg.datasource.open = false时生效）
 * @Author zhoujf
 *
 */
@Slf4j
@Configuration
@MapperScan(value={"org.jeecg.modules.**.mapper*"})
public class MybatisPlusConfig {

    //需要注入的字段
    private static final String SYSTEM_TENANT_ID = "tenant_id";

    //忽略不需要注入的表
    private static final List<String> IGNORE_TENANT_TABLES = Lists.newArrayList("sys_tenant","base_area",
            "sys_dict","sys_dict_item","sys_category","cy_room_check_user","sys_app_version",
            "Statistics_ChangeShift","ParkGrant","ParkOrder","ParkSeller","cy_user",
            "ParkIORecord","ParkCarModel","ParkCarType","equip_sort","BaseParkinfo",
            "statistics_gather","equip_event_sort","equip_collect_item","equip_data_collector",
            "equip_data_collector_code","charge_invoice_bw_config","equip_data_collector_type","sys_permission",
            "equip_data_current","equip_data_event","equip_data_record","wx_user",
            "car_parking_record","car_merchant_derate","car_merchant_order","charge_order_review","charge_order_review_detail",
            "car_order","car_merchant","car_derate_details","wx_car_pay_config","charge_method","meter_order","meter_charge_info",
             "meter","meter_fee","meter_account","meter_change","meter_control_switch",
            "meter_account","meter_use","meter_read","car_tencent_car_no","charge_fee_category");

    /**
     *  分页插件
     */
    @Bean
    public PaginationInterceptor paginationInterceptor() {

        PaginationInterceptor paginationInterceptor = new PaginationInterceptor();
        /*
         * 【测试多租户】 SQL 解析处理拦截器<br>
         * 这里固定写成住户 1 实际情况你可以从cookie读取，因此数据看不到 【 麻花藤 】 这条记录（ 注意观察 SQL ）<br>
         */
        List<ISqlParser> sqlParserList = new ArrayList<>();
        TenantSqlParser tenantSqlParser = new TenantSqlParser();
        tenantSqlParser.setTenantHandler(new TenantHandler() {
            @Override
            public Expression getTenantId() {
                return TenantUtil.get();
            }

            @Override
            public String getTenantIdColumn() {
                return SYSTEM_TENANT_ID;
            }

            @Override
            public boolean doTableFilter(String tableName) {
                // true - 忽略表,不自动添加tenant_id  false - 需要添加tenant_id
                // 忽略掉一些表：如租户表（provider）本身不需要执行这样的处理。
                boolean ignore = IGNORE_TENANT_TABLES.stream().anyMatch((e) -> e.equals(tableName));
                return ignore;
            }
        });

        sqlParserList.add(tenantSqlParser);
        //暂时注释，开发完成再放开
        paginationInterceptor.setSqlParserList(sqlParserList);



//        paginationInterceptor.setSqlParserFilter(new ISqlParserFilter() {
//            @Override
//            public boolean doFilter(MetaObject metaObject) {
//                MappedStatement ms = PluginUtils.getMappedStatement(metaObject);
//                // 过滤自定义查询此时无租户信息约束【 麻花藤 】出现
//                if ("com.baomidou.springboot.mapper.UserMapper.selectListBySQL".equals(ms.getId())) {
//                    return true;
//                }
//                return false;
//            }
//        });
        return paginationInterceptor;
    }

    @Bean(name = "performanceInterceptor")
    public PerformanceInterceptor performanceInterceptor() {
        return new PerformanceInterceptor();
    }

    /**
     * mybatisplus3.1.1之前版本
     * 增加逻辑删除支持
     * @return
     */
    /*@Bean
    public ISqlInjector sqlInjector() {
        return new LogicSqlInjector();
    }*/
    
//    /**
//     * mybatis-plus SQL执行效率插件【生产环境可以关闭】
//     */
//    @Bean
//    public PerformanceInterceptor performanceInterceptor() {
//        return new PerformanceInterceptor();
//    }
    
   
}
